<?php
class ControllerCommunitySearch extends Controller{
    public function index(){
        $this->language->load('community/search');
        $this->language->load('community/community_header');

        $this->document->setTitle($this->language->get('heading_title'));

        $this->load->model('community/search');

        //detect if user login
        if($this->customer->isLogged()){
            $this->data['is_user_login']=TRUE;
        }else{
            $this->data['is_user_login']=FALSE;
        }

        if(isset($this->request->get['kw']) || (isset($this->request->get['mode']) && $this->request->get['mode']=='unanswered')){
            $this->data['show_result']=TRUE;

            if(isset($this->request->get['kw'])){
                $pattern=array('+','&quot;');
                $replacement=array('%2B',"%22");

                $keyword_url=str_replace($pattern,$replacement,$this->request->get['kw']);
                $url='kw=' . $keyword_url;

                if(isset($this->request->get['au'])){
                    $url.='&au=' . $this->request->get['au'];
                }

                if(isset($this->request->get['if'])){
                    $url.='&if=' . $this->request->get['if'];
                }

                if(isset($this->request->get['sw'])){
                    $url.='&sw=' . $this->request->get['sw'];
                }

                if(isset($this->request->get['sb'])){
                    $url.='&sb=' . $this->request->get['sb'];
                }

                if(isset($this->request->get['or'])){
                    $url.='&or=' . $this->request->get['or'];
                }

                if(isset($this->request->get['lr'])){
                    $url.='&lr=' . $this->request->get['lr'];
                }
            }else{
                $url='mode=unanswered';
            }

            $pagination = new Pagination();

            if(isset($this->request->get['kw'])){
                $pagination->total=$this->model_community_search->getSearchResultTotal($this->request->get);
            }else{
                $pagination->total=$this->model_community_search->getUnansweredTopicTotal();
            }

            $this->data['text_found_matches']=sprintf($this->language->get('text_found_matches'),$pagination->total, isset($this->request->get['kw']) ? $this->request->get['kw'] : $this->language->get('unanswered_topics'));

            if (isset($this->request->get['page'])) {
                $page = $this->request->get['page'];
            } else {
                $page = 1;
            }

            $pagination->page = $page;
            $pagination->limit = 10;
            $pagination->url = $this->url->link('community/search',$url . '&page={page}');

            $this->data['pagination'] = $pagination->render();

            $start=($page-1)*$pagination->limit;

            $this->data['results']=array();

            if(isset($this->request->get['kw'])){
                $results=$this->model_community_search->getSearchResult($this->request->get,$start,$pagination->limit);
            }else{
                $results=$this->model_community_search->getUnansweredTopics($start,$pagination->limit);
            }

            $i=0;
            foreach($results as $result){
                $this->data['results'][]=array(
                    'post_link'        =>      $this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' .  $result['topic_id'] . '&pid=' . $result['post_id'] . '#' . $result['post_id'],'SSL'),

                    'post_time'         =>      date($this->language->get('date_time_format_long'),$result['post_time']),
                    'user_link'         =>      $this->url->link('community/profile','uid=' . $result['user_id'] ,'SSL'),
                    'username'          =>      $result['username'],
                    'forum_link'        =>      $this->url->link('community/viewforum','fid=' . $result['forum_id'] ,'SSL'),
                    'forum_name'        =>      $result['forum_name'],
                    'topic_link'        =>      $this->url->link('community/viewtopic','fid=' . $result['forum_id'] . '&tid=' .  $result['topic_id'],'SSL'),
                    'topic_title'       =>      $result['topic_title'],
                    'topic_views'       =>      $result['topic_views'],
                    'topic_replies'     =>      $result['topic_replies']
                );

                //add background color to keyword in subject & message text
                if(isset($this->request->get['kw'])){
                    $keyword=trim($this->request->get['kw'],'+-*"');

                    $strs=explode(' ',str_replace('&quot;','',trim($keyword)));

                    foreach($strs as $str){
                        $text_pattern[]='/(' . $str . ')/i';
                    }

                    for($j=0;$j<count($text_pattern);$j++){
                        $text_replacement[]='<span style="display:inline;background-color:#F3BFCC;">\1</span>';
                    }

                    if(isset($this->request->get['sw'])){
                        if($this->request->get['sw']=='ps' || $this->request->get['sw']=='ts'){
                            $this->data['results'][$i]['post_subject']=preg_replace($text_pattern,$text_replacement,$result['post_subject']);
                            $this->data['results'][$i]['post_text']=$this->parseSmiles($this->parseBbcode($this->parseSpacing($this->parseURL($result['post_text']))));
                        }elseif($this->request->get['sw']=='pm' || $this->request->get['sw']=='tm'){
                            $this->data['results'][$i]['post_subject']=$result['post_subject'];
                            $this->data['results'][$i]['post_text']=preg_replace($text_pattern,$text_replacement,$this->parseSmiles($this->parseBbcode($this->parseSpacing($this->parseURL($result['post_text'])))));
                        }else{
                            $this->data['results'][$i]['post_subject']=preg_replace($text_pattern,$text_replacement,$result['post_subject']);
                            $this->data['results'][$i]['post_text']=preg_replace($text_pattern,$text_replacement,$this->parseSmiles($this->parseBbcode($this->parseSpacing($this->parseURL($result['post_text'])))));
                        }
                    }else{
                        $this->data['results'][$i]['post_subject']=preg_replace($text_pattern,$text_replacement,$result['post_subject']);
                        $this->data['results'][$i]['post_text']=preg_replace($text_pattern,$text_replacement,$this->parseSmiles($this->parseBbcode($this->parseSpacing($this->parseURL($result['post_text'])))));
                    }
                }else{
                    $this->data['results'][$i]['post_subject']=$result['post_subject'];
                    $this->data['results'][$i]['post_text']=$this->parseSmiles($this->parseBbcode($this->parseSpacing($this->parseURL($result['post_text']))));
                }

                $i++;
            }
        }else{
            $this->data['show_result']=FALSE;
        }

        $this->data['breadcrumbs']=array();

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('common/home'),
            'text'      =>      $this->language->get('text_home'),
            'separator'=>      FALSE
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/community'),
            'text'      =>      $this->language->get('text_community'),
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/search'),
            'text'      =>      $this->language->get('text_search'),
            'separator' =>      $this->language->get('text_separator')
        );

        if (isset($this->request->get['kw'])) {
            $this->data['search_button_value'] = trim($this->request->get['kw']);
        } else {
            $this->data['search_button_value'] = '';
        }
        $this->data['text_search_forum']=$this->language->get('text_search_forum');
        $this->data['text_search_submit_button_value']=$this->language->get('text_search_submit_button_value');
        $this->data['text_advanced_search']=$this->language->get('text_advanced_search');
        $this->data['text_advanced_search_button_title']=$this->language->get('text_advanced_search_button_title');
        $this->data['text_search_query']=$this->language->get('text_search_query');
        $this->data['text_keyword_tip']=$this->language->get('text_keyword_tip');
        $this->data['text_author_tip']=$this->language->get('text_author_tip');
        $this->data['text_search_option']=$this->language->get('text_search_option');
        $this->data['text_all_open_fourms']=$this->language->get('text_all_open_fourms');
        $this->data['text_post_subject_message']=$this->language->get('text_post_subject_message');
        $this->data['text_post_subject_only']=$this->language->get('text_post_subject_only');
        $this->data['text_post_message_only']=$this->language->get('text_post_message_only');
        $this->data['text_topic_subject_message']=$this->language->get('text_topic_subject_message');
        $this->data['text_topic_subject_only']=$this->language->get('text_topic_subject_only');
        $this->data['text_topic_message_only']=$this->language->get('text_topic_message_only');
        $this->data['text_last_post_time']=$this->language->get('text_last_post_time');
        $this->data['text_topic_time']=$this->language->get('text_topic_time');
        $this->data['text_topic_views']=$this->language->get('text_topic_views');
        $this->data['text_topic_replies']=$this->language->get('text_topic_replies');
        $this->data['text_forum']=$this->language->get('text_forum');
        $this->data['text_author']=$this->language->get('text_author');
        $this->data['text_descending']=$this->language->get('text_descending');
        $this->data['text_ascending']=$this->language->get('text_ascending');
        $this->data['text_all_result']=$this->language->get('text_all_result');
        $this->data['text_one_day']=$this->language->get('text_one_day');
        $this->data['text_one_week']=$this->language->get('text_one_week');
        $this->data['text_two_week']=$this->language->get('text_two_week');
        $this->data['text_one_month']=$this->language->get('text_one_month');
        $this->data['text_three_month']=$this->language->get('text_three_month');
        $this->data['text_six_month']=$this->language->get('text_six_month');
        $this->data['text_one_year']=$this->language->get('text_one_year');
        $this->data['text_by']=$this->language->get('text_by');
        $this->data['text_forum']=$this->language->get('text_forum');
        $this->data['text_topic']=$this->language->get('text_topic');
        $this->data['text_views']=$this->language->get('text_views');
        $this->data['text_replies']=$this->language->get('text_replies');
        $this->data['text_no_result']=$this->language->get('text_no_result');

        //entry
        $this->data['entry_keyword']=$this->language->get('entry_keyword');
        $this->data['entry_author']=$this->language->get('entry_author');
        $this->data['entry_search_forum']=$this->language->get('entry_search_forum');
        $this->data['entry_search_within']=$this->language->get('entry_search_within');
        $this->data['entry_sort_by']=$this->language->get('entry_sort_by');
        $this->data['entry_search_time_limit']=$this->language->get('entry_search_time_limit');

        //button
        $this->data['button_search']=$this->language->get('button_search');

        $this->data['forums']=array();
        $this->data['sub_forums']=array();

        $forums=$this->model_community_search->getForums();

        foreach($forums as $forum){
            $this->data['forums'][]=array(
                'forum_id'      =>      $forum['forum_id'],
                'forum_name'    =>      $forum['forum_name']
            );

            $subForums=$this->model_community_search->getSubForums($forum['forum_id']);

            foreach($subForums as $subForum){
                $this->data['sub_forums'][$forum['forum_id']][]=array(
                    'forum_id'      =>      $subForum['forum_id'],
                    'forum_name'    =>      '&nbsp;&nbsp;' . $subForum['forum_name']
                );
            }
        }

        if(file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/community/search.tpl')){
            $this->template=$this->config->get('config_template') . '/template/community/search.tpl';
        }else{
            $this->template='default/template/community/search.tpl';
        }

        $this->children = array(
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header',
            'community/community_header'
        );

        $this->response->setOutput($this->render());
    }

    private function parseSpacing($str){
        $str=nl2br($str);
        $str = str_replace("\t", '&nbsp; &nbsp;', $str);
        $str = str_replace('  ', '&nbsp; ', $str);
        $str = str_replace('  ', ' &nbsp;', $str);

        return $str;
    }

    private function parseBbcode($str){
        if($this->config->get('bbcode_parsing_enable')){
            $pattern=array();
            $pattern[]='/\[size=(\d+)\](.*)\[\/size\]/Uis';
            $pattern[]='/\[b\](.*)\[\/b\]/Uis';
            $pattern[]='/\[i\](.*)\[\/i\]/Uis';
            $pattern[]='/\[u\](.*)\[\/u\]/Uis';
            $pattern[]='/\[color=(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z\-]+)\](.*)\[\/color\]/Uis';

            if($this->config->get('bbcode_url_parsing_enable')){
                $pattern[]='/\[url\](.*)\[\/url\]/Uis';
                $pattern[]='/\[url=([^\[]+?)\](.*)\[\/url\]/Uis';
            }

            $pattern[]='/\[quote(?!&quot;.*&quot;)\](.*)\[\/quote\]/Uis';
            $pattern[]='/\[quote=&quot;(.*)&quot;\](.*)\[\/quote\]/Uis';
            $pattern[]='/\[code\](.*)\[\/code\]/Uis';

            if($this->config->get('bbcode_img_parsing_enable')){
                $pattern[]='/\[img\](.*)\[\/img\]/Uis';
            }

            if($this->config->get('bbcode_flash_parsing_enable')){
                $pattern[]='/\[flash\](.*)\[\/flash\]/Uis';
            }

            $pattern[]='/\[youtube\](http:\/\/)?(www\.)?youtube.com\/watch\?v=(.*)(&amp;\w*=.*)?\[\/youtube\]/Uis';

            $replace=array();
            $replace[]='<span style="font-size:\1%;">\2</span>';
            $replace[]='<strong>\1</strong>';
            $replace[]='<em>\1</em>';
            $replace[]='<span style="text-decoration:underline;">\1</span>';
            $replace[]='<span style="color:\1;">\2</span>';

            if($this->config->get('bbcode_url_parsing_enable')){
                $replace[]='<a href="\1" target="_blank">\1</a>';
                $replace[]='<a href="\1" target="_blank">\2</a>';
            }

            $replace[]='<blockquote class="bbcode_uncited"><div>\1</div></blockquote>';
            $replace[]='<blockquote class="bbcode_uncited"><div><dl><dt>\1 Wrote:</dt><dd>\2</dd></dl></div></blockquote>';
            $replace[]='<dl class="bbcode_code"><dt>CODE: <a href="javascript:void(0)" onclick="selectCode(this); return FALSE;">SELECT ALL</a></dt><dd><code>\1</code></dd></dl>';

            if($this->config->get('bbcode_img_parsing_enable')){
                $replace[]='<img src="\1" />';
            }

            if($this->config->get('bbcode_flash_parsing_enable')){
                $replace[]='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="400" width="480"><param name="quality" value="high" /><param name="movie" value="\1" /><embed height="400" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="\1" type="application/x-shockwave-flash" width="480"></embed></object>';
            }

            $replace[]='<iframe width="560" height="315" src="http://www.youtube.com/embed/\3" frameborder="0" allowfullscreen></iframe>';

            $str=preg_replace($pattern,$replace,$str);
        }

        return $str;
    }

    private function parseSmiles($str){
        if($this->config->get('smiles_parsing_enable')){
            $smileCode=array(
                ':D',
                ':)',
                ';)',
                ':(',
                ':o',
                ':shock:',
                ':?',
                '8-)',
                ':lol:',
                ':x',
                ':P',
                ':-oops:',
                ':cry:',
                ':evil:',
                ':twisted:',
                ':roll:',
                ':!:',
                ':-?:',
                ':idea:',
                ':arrow:',
                ':|',
                ':mrgreen:',
                ':geek:',
                ':ugeek:',
            );

            $smileImage=array(
                '<img src="catalog/view/theme/default/image/smilies/01_very_happy.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/02_smile.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/03_wink.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/04_sad.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/05_surprised.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/06_shocked.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/07_confused.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/08_cool.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/09_langhing.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/10_mad.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/11_razz.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/12_embarrassed.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/13_cry.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/14_evil_or_very_mad.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/15_twisted_evil.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/16_rolling_eyes.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/17_exclamation.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/18_question.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/19_idea.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/20_arrow.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/21_neutral.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/22_mr._green.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/23_geek.gif" />',
                '<img src="catalog/view/theme/default/image/smilies/24_uber_geek.gif" />'
            );

            $str=str_replace($smileCode,$smileImage,$str);
        }

        return $str;
    }

    private function parseURL($str){
        if($this->config->get('auto_url_parsing_enable')){
            $pattern=$replace=array();
            // matches an "xxxx://yyyy" URL at the start of a line, or after a space.xxxx can only be alpha characters. yyyy is anything up to the first space, newline, comma, double quote or <
            $pattern[]='/(^|[\n ])([\w]+?:\/\/[^ \"\n\r\t<]*)/is';
            // matches a "www|ftp.xxxx.yyyy[/zzzz]" kinda lazy URL thing.Must contain at least 2 dots. xxxx contains either alphanum, or "-". zzzz is optional.. will contain everything up to the first space, newline,comma, double quote or <.
            $pattern[]='/(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)/is';
            // matches an email@domain type address at the start of a line, or after a space. Note: Only the followed chars are valid; alphanums, "-", "_" and or ".".
            $pattern[]='/(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)/i';

            $replace[]='\\1<a href="\\2" target="_blank">\\2</a>';
            $replace[]='\\1<a href="http://\\2" target="_blank">\\2</a>';
            $replace[]='\\1<a href="mailto:\\2@\\3">\\2@\\3</a>';

            $str=preg_replace($pattern,$replace,$str);
        }

        return $str;
    }
}
?>